package com.sls.api.game.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.sls.api.game.constant.Constant;
import com.sls.api.game.pojo.EnLinkRequestInfo;
import com.sls.api.util.IpUtil;
import com.sls.api.util.PropertiesUtil;
import com.sls.api.util.UtilMD5Encryption;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;

/**
 * 恩联异步请求接口
 * 
 * @author cx
 * 
 */
public class EnLinkTradeStatusServlet extends SuperServlet {

	private static final long serialVersionUID = 5749373038025175155L;
	
	private static Logger log = Logger
			.getLogger(EnLinkTradeStatusServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setStatus(HttpServletResponse.SC_OK);
		log.info("来找卡异步通知的参数：" + req.getParameter("parameter"));
		String parameter = req.getParameter("parameter");
		if (StringUtils.isEmpty(parameter)) {
			resp.getWriter().write("缺少参数[parameter]!");
			close(resp.getWriter());
			return;
		}
		EnLinkRequestInfo enLinkInfo = null;
		Gson gson = CommonUtil.gson();
		try {
			if (StringUtils.isNotEmpty(parameter)) {
				parameter = parameter.trim();
				enLinkInfo = gson.fromJson(parameter, EnLinkRequestInfo.class);
				if (enLinkInfo == null) {
					resp.getWriter().write("参数格式错误!");
					close(resp.getWriter());
					return;
				}
				boolean flag = this.checkData(enLinkInfo, resp);
				if (flag) {

					String prodName = enLinkInfo.getProdName();
					String remark = enLinkInfo.getRemark();
					String prodContent = enLinkInfo.getProdContent();
					prodName = URLDecoder.decode(prodName, "UTF-8");
					enLinkInfo.setProdName(prodName);
					if (StringUtils.isNotEmpty(remark)) {
						remark = URLDecoder.decode(remark, "UTF-8");
						enLinkInfo.setRemark(remark);
					}
					if (StringUtils.isNotEmpty(prodContent)) {
						prodContent = URLDecoder.decode(prodContent, "UTF-8");
						enLinkInfo.setProdContent(prodContent);
					}
					
					log.info("恩联异步推送的结果为：" + "\n恩联订单号：" + enLinkInfo.getTranaNo() +
							"\n 产品名称:" + prodName 
							+  "\n 交易状态:" + enLinkInfo.getResultCode());
					
					SocketDTO dto = this.orgMsg(enLinkInfo, req);
					Head head = dto.getHead();
					String resCode = head.getResponseCode();
					if (Constant.SUCCESS.equals(resCode)) {
						resp.getWriter().write("success");
						close(resp.getWriter());
					} else {
						resp.getWriter().write("未知错误!");
						close(resp.getWriter());
					}
				}
			}
		} catch (Exception e) {
			resp.getWriter().write("未知错误!");
			close(resp.getWriter());
		}
	}

	/**
	 * 组织gson报文
	 * 
	 * @param enLinkInfo
	 * @param req
	 * @return
	 */
	private SocketDTO orgMsg(EnLinkRequestInfo enLinkInfo,
			HttpServletRequest req) {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.EN_LINK_ASYNC);
		head.setIp(IpUtil.getIpAddr(req)); // ---------恩联IP
		head.setUserId("0"); // ---------恩联用户ID
		return super.send(head, enLinkInfo);
	}

	/**
	 * 数据校验
	 * 
	 * @param enLinkInfo
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	private boolean checkData(EnLinkRequestInfo enLinkInfo,
			HttpServletResponse resp) throws IOException {
		StringBuilder sb = new StringBuilder();
		String forginOrderNo = enLinkInfo.getForginOrderNo();
		String prodCode = enLinkInfo.getProdCode();
		String prodContent = enLinkInfo.getProdContent();
		String prodName = enLinkInfo.getProdName();
		String prodNum = enLinkInfo.getProdNum();
		String tranaNo = enLinkInfo.getTranaNo();
		String time = enLinkInfo.getTime();
		String resultCode = enLinkInfo.getResultCode();
		String remark = enLinkInfo.getRemark();
		String signStr = enLinkInfo.getSign();
		if (StringUtils.isNotEmpty(forginOrderNo)) {
			sb.append(forginOrderNo);
			sb.append("|");
		}
		if (StringUtils.isNotEmpty(prodCode)) {
			sb.append(prodCode);
			sb.append("|");
		}
		if (StringUtils.isNotEmpty(prodContent)) {
			sb.append(enLinkInfo.getProdContent());
			sb.append("|");
		}
		if (StringUtils.isNotEmpty(prodName)) {
			sb.append(prodName);
			sb.append("|");
		}
		if (StringUtils.isNotEmpty(prodNum)) {
			sb.append(prodNum);
			sb.append("|");
		}
		if (StringUtils.isNotEmpty(remark)) {
			sb.append(remark);
			sb.append("|");
		}
		if (StringUtils.isNotEmpty(resultCode)) {
			sb.append(resultCode);
			sb.append("|");
		}
		if (StringUtils.isNotEmpty(time)) {
			sb.append(time);
			sb.append("|");
		}
		if (StringUtils.isNotEmpty(tranaNo)) {
			sb.append(tranaNo);
		}
		String data = sb.toString();
		String md5_key = PropertiesUtil.getValue("md5.key");
		String sign = UtilMD5Encryption.createMD5EncryptionOfUTF8(data + "|"
				+ md5_key);
		sign = UtilMD5Encryption
				.createMD5EncryptionOfUTF8(sign + "|" + md5_key);
		if (sign.equals(signStr)) {
			return true;
		} else {
			resp.getWriter().write("签名验证失败!");
			close(resp.getWriter());
			return false;
		}

	}

	/**
	 * 关闭资源
	 * 
	 * @param pw
	 */
	private void close(PrintWriter pw) {
		if (pw != null) {
			pw.flush();
			pw.close();
		}
	}
}
